import React, { useEffect, useState, useRef } from 'react';
import { View, StyleSheet, Text, TouchableOpacity, TextInput, FlatList, Alert } from 'react-native';
import {
    RTCPeerConnection,
    RTCIceCandidate,
    RTCSessionDescription,
    RTCView,
    MediaStream,
} from 'react-native-webrtc';
import io, { Socket } from 'socket.io-client';
import Adapt from './../../ulits/Adapt';

interface NavigationProps {
    navigation: {
        goBack: () => void;
    };
    route: {
        params: {
            roomId: string;
        };
    };
}

interface SignalingData {
    roomId: string;
    offer?: RTCSessionDescription;
    answer?: RTCSessionDescription;
    candidate?: RTCIceCandidate;
}

interface RTCIceCandidateEvent {
    candidate: RTCIceCandidate | null;
}

interface RTCTrackEvent {
    streams: MediaStream[];
}

interface CommentData {
    senderId: string;
    message: string;
    timestamp: number;
}

const configuration = {
    iceServers: [
        { urls: 'stun:stun.l.google.com:19302' },
    ],
};

export default function Watch({ navigation, route }: NavigationProps) {
    const [isConnected, setIsConnected] = useState(false);
    const [remoteStream, setRemoteStream] = useState<MediaStream | null>(null);
    const [roomId, setRoomId] = useState('');
    const [connectionState, setConnectionState] = useState<string>('未连接');
    const [isReadyToWatch, setIsReadyToWatch] = useState(false);
    const [hasReceivedIceCandidate, setHasReceivedIceCandidate] = useState(false);
    const [hasReceivedOffer, setHasReceivedOffer] = useState(false);
    const [iceConnectionState, setIceConnectionState] = useState<string>('');
    const [signalingState, setSignalingState] = useState<string>('');
    const [commentInput, setCommentInput] = useState<string>('');
    const [comments, setComments] = useState<CommentData[]>([]);
    const socketRef = useRef<Socket | null>(null);
    const peerConnectionRef = useRef<RTCPeerConnection | null>(null);
    const iceCandidatesQueue = useRef<RTCIceCandidate[]>([]);

    useEffect(() => {
        // 从路由参数获取房间ID
        const roomId = route.params?.roomId;
        console.log('获取到房间ID:', roomId);
        if (roomId) {
            setRoomId(roomId);
            connectToStream(roomId);
        } else {
            console.error('未获取到房间ID');
            setConnectionState('错误：未获取到房间ID');
        }
        return () => {
            if (peerConnectionRef.current) {
                peerConnectionRef.current.close();
            }
            if (socketRef.current) {
                socketRef.current.disconnect();
            }
        };
    }, [route.params]);

    useEffect(() => {
        if (socketRef.current) {
            // 监听直播结束事件
            socketRef.current.on('live-ended', ({ roomId }) => {
                console.log('收到直播结束通知');
                // 清理资源
                if (peerConnectionRef.current) {
                    peerConnectionRef.current.close();
                }
                if (remoteStream) {
                    remoteStream.getTracks().forEach(track => track.stop());
                }
                // 显示提示并返回
                Alert.alert('直播已结束', '主播已结束直播', [
                    { text: '确定', onPress: () => navigation.goBack() }
                ]);
            });

            return () => {
                socketRef.current?.off('live-ended');
            };
        }
    }, [navigation, remoteStream]);

    const addIceCandidate = async (candidate: RTCIceCandidate) => {
        try {
            if (!peerConnectionRef.current) {
                console.log('PeerConnection未创建，将ICE候选加入队列');
                iceCandidatesQueue.current.push(candidate);
                return;
            }

            if (!peerConnectionRef.current.remoteDescription) {
                console.log('远程描述未设置，将ICE候选加入队列');
                iceCandidatesQueue.current.push(candidate);
                return;
            }

            console.log('添加ICE候选到PeerConnection');
            await peerConnectionRef.current.addIceCandidate(candidate);
            console.log('ICE候选添加成功');
        } catch (error) {
            console.error('添加ICE候选时出错:', error);
            setConnectionState('错误：添加ICE候选失败');
        }
    };

    const processIceCandidatesQueue = async () => {
        if (!peerConnectionRef.current) {
            console.log('PeerConnection未创建，无法处理ICE候选队列');
            return;
        }

        if (!peerConnectionRef.current.remoteDescription) {
            console.log('远程描述未设置，无法处理ICE候选队列');
            return;
        }

        console.log('处理ICE候选队列，队列长度:', iceCandidatesQueue.current.length);
        const candidates = [...iceCandidatesQueue.current];
        iceCandidatesQueue.current = [];

        for (const candidate of candidates) {
            try {
                console.log('添加队列中的ICE候选');
                await peerConnectionRef.current.addIceCandidate(candidate);
                console.log('队列中的ICE候选添加成功');
            } catch (error) {
                console.error('添加队列中的ICE候选时出错:', error);
                setConnectionState('错误：处理ICE候选队列失败');
            }
        }
    };

    const connectToStream = async (roomId: string) => {
        try {
            setConnectionState('正在连接信令服务器...');
            console.log('开始连接信令服务器...');
            socketRef.current = io('http://192.168.46.222:3020');
            
            socketRef.current.on('connect', () => {
                console.log('已连接到信令服务器');
                setConnectionState('已连接到信令服务器');
            });

            socketRef.current.on('connect_error', (error) => {
                console.error('连接信令服务器失败:', error);
                setConnectionState('错误：连接信令服务器失败');
            });

            socketRef.current.on('disconnect', () => {
                console.log('与信令服务器断开连接');
                setConnectionState('与信令服务器断开连接');
            });

            // 处理offer
            socketRef.current.on('offer', async (data: SignalingData) => {
                console.log('收到offer:', data);
                setConnectionState('收到offer');
                setHasReceivedOffer(true);
                if (peerConnectionRef.current && data.offer) {
                    try {
                        console.log('设置远程描述(offer)...');
                        setConnectionState('正在设置远程描述...');
                        await peerConnectionRef.current.setRemoteDescription(
                            new RTCSessionDescription(data.offer)
                        );
                        console.log('远程描述设置成功');

                        // 设置远程描述成功后，立即处理ICE候选队列
                        await processIceCandidatesQueue();
                        setConnectionState('远程描述设置成功，ICE候选处理完成');

                        // 自动创建和发送answer
                        console.log('创建answer...');
                        const answer = await peerConnectionRef.current.createAnswer();
                        console.log('answer创建成功:', answer);

                        console.log('设置本地描述(answer)...');
                        await peerConnectionRef.current.setLocalDescription(answer);
                        console.log('本地描述设置成功');

                        socketRef.current?.emit('answer', {
                            roomId,
                            answer: peerConnectionRef.current.localDescription,
                        });
                        console.log('answer已发送');
                        setConnectionState('answer已发送');
                        setIsReadyToWatch(true);
                    } catch (error) {
                        console.error('处理offer时出错:', error);
                        setConnectionState('错误：处理offer失败');
                    }
                }
            });

            // 处理ICE候选
            socketRef.current.on('ice-candidate', async (data: SignalingData) => {
                console.log('收到ICE候选:', data);
                setConnectionState('收到ICE候选');
                setHasReceivedIceCandidate(true);
                if (data.candidate) {
                    await addIceCandidate(new RTCIceCandidate(data.candidate));
                }
            });

            // 处理评论
            socketRef.current.on('comment', (data: CommentData) => {
                console.log('收到评论:', data);
                setComments(prevComments => [...prevComments, data]);
            });

            // 处理错误
            socketRef.current.on('error', (error) => {
                console.error('信令错误:', error);
                setConnectionState('错误：信令错误');
            });

            console.log('创建PeerConnection...');
            setConnectionState('正在创建PeerConnection...');
            peerConnectionRef.current = new RTCPeerConnection(configuration);

            if (peerConnectionRef.current) {
                // 处理远程流
                (peerConnectionRef.current as any).ontrack = (event: RTCTrackEvent) => {
                    console.log('收到远程流');
                    console.log('远程流轨道:', event.streams[0].getTracks().map(track => ({
                        kind: track.kind,
                        enabled: track.enabled,
                        muted: track.muted,
                        readyState: track.readyState
                    })));
                    setRemoteStream(event.streams[0]);
                    setConnectionState('已收到远程流');
                };

                // 处理ICE候选
                (peerConnectionRef.current as any).onicecandidate = (event: RTCIceCandidateEvent) => {
                    if (event.candidate && socketRef.current) {
                        console.log('发送ICE候选:', event.candidate);
                        socketRef.current.emit('ice-candidate', {
                            roomId,
                            candidate: event.candidate,
                        });
                    }
                };

                // 监听ICE连接状态变化
                (peerConnectionRef.current as any).oniceconnectionstatechange = () => {
                    const state = peerConnectionRef.current?.iceConnectionState;
                    console.log('ICE连接状态变化:', state);
                    setIceConnectionState(state || '');
                    
                    if (state === 'connected' || state === 'completed') {
                        setConnectionState('ICE连接已建立');
                    } else if (state === 'failed' || state === 'disconnected' || state === 'closed') {
                        setConnectionState(`ICE连接${state}`);
                    }
                };

                // 监听信令状态变化
                (peerConnectionRef.current as any).onsignalingstatechange = () => {
                    const state = peerConnectionRef.current?.signalingState;
                    console.log('信令状态变化:', state);
                    setSignalingState(state || '');
                };

                // 监听连接状态变化
                (peerConnectionRef.current as any).onconnectionstatechange = () => {
                    const state = peerConnectionRef.current?.connectionState;
                    console.log('连接状态变化:', state);
                    setConnectionState(`连接状态: ${state}`);
                };

                // 监听ICE收集状态
                (peerConnectionRef.current as any).onicegatheringstatechange = () => {
                    const state = peerConnectionRef.current?.iceGatheringState;
                    console.log('ICE收集状态:', state);
                };
            }

            // 加入房间
            if (socketRef.current) {
                console.log('加入房间:', roomId);
                setConnectionState('正在加入房间...');
                socketRef.current.emit('join-room', roomId);
            }

            setIsConnected(true);
        } catch (error) {
            console.error('连接直播失败:', error);
            setConnectionState('错误：连接直播失败');
        }
    };

    const leaveRoom = () => {
        if (peerConnectionRef.current) {
            peerConnectionRef.current.close();
        }
        if (socketRef.current) {
            socketRef.current.disconnect();
        }
        setRemoteStream(null);
        setIsConnected(false);
        navigation.goBack();
    };

    const sendComment = () => {
        if (socketRef.current && commentInput.trim() !== '') {
            const commentData: CommentData = {
                senderId: socketRef.current.id || '匿名用户', // Or a user ID
                message: commentInput.trim(),
                timestamp: Date.now(),
            };
            socketRef.current.emit('comment', { roomId, comment: commentData });
            setCommentInput(''); // Clear input
        }
    };

    return (
        <View style={styles.container}>
            <View style={styles.streamContainer}>
                {remoteStream ? (
                    <>
                        <RTCView
                            streamURL={remoteStream.toURL()}
                            style={styles.remoteStream}
                            objectFit="cover"
                            mirror={false}
                        />
                        <Text style={styles.streamInfo}>
                            流状态: {remoteStream.active ? '活跃' : '非活跃'}{'\n'}
                            轨道数: {remoteStream.getTracks().length}{'\n'}
                            视频轨道: {remoteStream.getVideoTracks().length}{'\n'}
                            音频轨道: {remoteStream.getAudioTracks().length}
                        </Text>
                    </>
                ) : (
                    <Text style={styles.loadingText}>正在连接直播...</Text>
                )}
                <Text style={styles.connectionState}>
                    {connectionState}{'\n'}
                    ICE状态: {iceConnectionState}{'\n'}
                    信令状态: {signalingState}{'\n'}
                    是否收到ICE候选: {hasReceivedIceCandidate ? '是' : '否'}{'\n'}
                    是否收到offer: {hasReceivedOffer ? '是' : '否'}
                </Text>

                <View style={styles.topRightButtonsContainer}>
                    {!isReadyToWatch && hasReceivedIceCandidate && hasReceivedOffer && (
                        <TouchableOpacity 
                            style={styles.startButton} 
                            onPress={() => connectToStream(roomId)}
                        >
                            <Text style={styles.startButtonText}>开始观看</Text>
                        </TouchableOpacity>
                    )}
                    <TouchableOpacity style={styles.leaveButton} onPress={leaveRoom}>
                        <Text style={styles.leaveButtonText}>退出直播</Text>
                    </TouchableOpacity>
                </View>

                <View style={styles.commentsContainer}>
                    <FlatList
                        data={comments}
                        keyExtractor={(item, index) => index.toString()}
                        renderItem={({ item }) => (
                            <View style={styles.commentItem}>
                                <Text style={styles.commentText}>
                                    {item.senderId.substring(0, 5)}: {item.message}
                                </Text>
                            </View>
                        )}
                        contentContainerStyle={styles.commentsListContent}
                    />
                    <View style={styles.commentInputContainer}>
                        <TextInput
                            style={styles.commentInput}
                            value={commentInput}
                            onChangeText={setCommentInput}
                            placeholder="输入评论..."
                            placeholderTextColor="#ccc"
                        />
                        <TouchableOpacity style={styles.sendButton} onPress={sendComment}>
                            <Text style={styles.sendButtonText}>发送</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'black',
    },
    streamContainer: {
        flex: 1,
        backgroundColor: '#000',
    },
    remoteStream: {
        flex: 1,
        backgroundColor: '#000',
    },
    loadingText: {
        color: 'white',
        fontSize: Adapt.adaptFontSize(16),
        textAlign: 'center',
        marginTop: Adapt.adapt(20),
    },
    topRightButtonsContainer: {
        position: 'absolute',
        top: Adapt.adapt(40),
        right: Adapt.adapt(20),
        flexDirection: 'row',
        zIndex: 10, // Ensure buttons are on top
    },
    leaveButton: {
        backgroundColor: '#FF3366',
        paddingHorizontal: Adapt.adapt(15),
        paddingVertical: Adapt.adapt(8),
        borderRadius: Adapt.adaptRadius(15),
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.8,
        shadowRadius: 2,
        elevation: 5,
        marginLeft: Adapt.adapt(10),
    },
    leaveButtonText: {
        color: 'white',
        fontSize: Adapt.adaptFontSize(14),
        fontWeight: 'bold',
    },
    streamInfo: {
        position: 'absolute',
        top: Adapt.adapt(40),
        left: Adapt.adapt(20),
        color: 'white',
        backgroundColor: 'rgba(0,0,0,0.6)',
        padding: Adapt.adapt(10),
        borderRadius: Adapt.adaptRadius(8),
    },
    connectionState: {
        position: 'absolute',
        top: Adapt.adapt(120),
        left: Adapt.adapt(20),
        color: 'white',
        backgroundColor: 'rgba(0,0,0,0.6)',
        padding: Adapt.adapt(10),
        borderRadius: Adapt.adaptRadius(8),
        fontSize: Adapt.adaptFontSize(12),
    },
    startButton: {
        backgroundColor: '#4CAF50',
        paddingHorizontal: Adapt.adapt(15),
        paddingVertical: Adapt.adapt(8),
        borderRadius: Adapt.adaptRadius(15),
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.8,
        shadowRadius: 2,
        elevation: 5,
    },
    startButtonText: {
        color: 'white',
        fontSize: Adapt.adaptFontSize(14),
        fontWeight: 'bold',
    },
    commentsContainer: {
        position: 'absolute',
        bottom: Adapt.adapt(100),
        left: Adapt.adapt(10),
        right: Adapt.adapt(10),
        height: Adapt.adapt(250),
        maxHeight: Adapt.adapt(300),
        backgroundColor: 'rgba(0,0,0,0.5)',
        borderRadius: Adapt.adaptRadius(15),
        paddingVertical: Adapt.adapt(10),
        paddingHorizontal: Adapt.adapt(10),
        justifyContent: 'flex-end',
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 5 },
        shadowOpacity: 0.5,
        shadowRadius: 5,
        elevation: 8,
    },
    commentsListContent: {
        paddingBottom: Adapt.adapt(10),
        paddingTop: Adapt.adapt(10),
    },
    commentItem: {
        backgroundColor: 'rgba(255,255,255,0.15)',
        borderRadius: Adapt.adaptRadius(10),
        padding: Adapt.adapt(10),
        marginBottom: Adapt.adapt(8),
    },
    commentText: {
        color: 'white',
        fontSize: Adapt.adaptFontSize(14),
        lineHeight: Adapt.adaptFontSize(18),
    },
    commentInputContainer: {
        flexDirection: 'row',
        marginTop: Adapt.adapt(10),
        alignItems: 'center',
    },
    commentInput: {
        flex: 1,
        backgroundColor: '#222',
        color: 'white',
        borderRadius: Adapt.adaptRadius(25),
        paddingHorizontal: Adapt.adapt(18),
        height: Adapt.adapt(45),
        fontSize: Adapt.adaptFontSize(15),
        borderWidth: 1,
        borderColor: '#555',
    },
    sendButton: {
        backgroundColor: '#1E90FF',
        borderRadius: Adapt.adaptRadius(25),
        paddingHorizontal: Adapt.adapt(20),
        paddingVertical: Adapt.adapt(12),
        marginLeft: Adapt.adapt(10),
        justifyContent: 'center',
        alignItems: 'center',
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 1 },
        shadowOpacity: 0.5,
        shadowRadius: 1,
        elevation: 3,
    },
    sendButtonText: {
        color: 'white',
        fontSize: Adapt.adaptFontSize(15),
        fontWeight: 'bold',
    },
});
